<template>
  <transition name="viewer-fade">
    <!-- 照片遮罩层 -->
    <div ref="el-image-viewer__wrapper" tabindex="-1" class="el-image-viewer__wrapper" :style="{ 'z-index': zIndex }">
      <div class="el-image-viewer__mask" />
      <!-- CLOSE -->
      <span class="el-image-viewer__btn el-image-viewer__close" @click="hide">
        <!-- <svg-icon icon-class="Wrongnumberblack" /> -->
        <i class="el-icon-close"></i>
      </span>
      <!-- ACTIONS -->
      <div class="el-image-viewer__btn el-image-viewer__actions">
        <div class="el-image-viewer__actions__inner">
          <template v-if="!isSingle">
            <i class="el-icon-arrow-left" :class="{ 'is-disabled': !infinite && isFirst }" @click="prev"></i>
            <i class="el-icon-arrow-right" :class="{ 'is-disabled': !infinite && isLast }" @click="next"></i>
            <!-- <svg-icon icon-class="zuoyou" :class="{ 'is-disabled': !infinite && isFirst }"
              style="transform: rotateZ(180deg)" @click="prev" />
            <svg-icon icon-class="zuoyou" :class="{ 'is-disabled': !infinite && isLast }" @click="next" /> -->
          </template>
          <!-- <svg-icon icon-class="fangdasuoxiaoY" @click="handleActions('zoomOut')" /> -->

          <i class="el-icon-zoom-out" @click="handleActions('zoomOut')"></i>
          <span class="scale">{{ scaleNum + "%" }}</span>
          <i class="el-icon-zoom-in" @click="handleActions('zoomIn')"></i>



          <!-- <svg-icon icon-class="fangdasuoxiaoX" @click="handleActions('zoomIn')" /> -->
          <!-- <i class="el-image-viewer__actions__divider" /> -->
          <!-- <svg-icon :icon-class="mode.icon" @click="toggleMode" /> -->
          <!-- <i class="el-image-viewer__actions__divider" /> -->



          <i class="el-icon-refresh-right" @click="handleActions('clocelise')"></i>

          <!-- <svg-icon icon-class="xuanzhuan" @click="handleActions('clocelise')" /> -->
          <div class="delete el-icon-delete" @click="$emit('delete', { index, urlList })"></div>
          <el-button class="secondaryBtn" @click="$emit('edit', { ...transform })">保存修改</el-button>
          <!-- <i class="el-icon-refresh-left" @click="handleActions('anticlocelise')"></i> -->
        </div>
      </div>
      <!-- CANVAS -->
      <div class="el-image-viewer__canvas">
        <template v-for="(url, i) in urlList">
          <!-- 全屏预览图 -->
          <img v-if="i === index" ref="img" :key="url.fileId" class="el-image-viewer__img" :src="currentImg"
            :style="imgStyle" @load="handleImgLoad" @error="handleImgError" @mousedown="handleMouseDown"
            alt="网络波动，加载失败" />
        </template>
      </div>
      <img :src="imgsrc" class="imgnone" alt="" />
      <img :src="imgsrcnext" class="imgnone" alt="" />
    </div>
  </transition>
</template>

<script>
import Big from "big.js";
function rafThrottle(fn) {
  let locked = false;
  return function (...args) {
    if (locked) return;
    locked = true;
    window.requestAnimationFrame((_) => {
      fn.apply(this, args);
      locked = false;
    });
  };
}
const isFirefox = function () {
  return !!window.navigator.userAgent.match(/firefox/i);
};
/* istanbul ignore next */
const on = function (element, event, handler) {
  if (element && event && handler) {
    element.addEventListener(event, handler, false);
  }
};
/* istanbul ignore next */
const off = function (element, event, handler) {
  if (element && event) {
    element.removeEventListener(event, handler, false);
  }
};
const Mode = {
  CONTAIN: {
    name: "contain",
    icon: "fullscreen",
  },
  ORIGINAL: {
    name: "original",
    icon: "dengbilizhanshi",
  },
};

const mousewheelEventName = isFirefox() ? "DOMMouseScroll" : "mousewheel";

export default {
  name: "AppImageViewer",

  props: {
    urlList: {
      type: Array,
      default: () => [],
    },
    zIndex: {
      type: Number,
      default: 2000,
    },
    onSwitch: {
      type: Function,
      default: () => { },
    },
    onClose: {
      type: Function,
      default: () => { },
    },
    initialIndex: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      index: this.initialIndex,
      isShow: false,
      infinite: true,
      loading: false,
      mode: Mode.CONTAIN,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false,
      },
      imgsrc: "",
      imgsrcnext: "",
    };
  },
  computed: {
    scaleNum() {
      return new Big(this.transform.scale).times(100);
    },
    isSingle() {
      return this.urlList.length <= 1;
    },
    isFirst() {
      return this.index === 0;
    },
    isLast() {
      return this.index === this.urlList.length - 1;
    },
    currentImg() {
      this.imgsrcload();
      console.log('21321', this.urlList[this.index]);
      return this.urlList[this.index].fileUrl || '';
    },
    imgStyle() {
      const { scale, deg, offsetX, offsetY, enableTransition } = this.transform;
      const style = {
        transform: `scale(${scale}) rotate(${deg}deg)`,
        transition: enableTransition ? "transform .3s" : "",
        "margin-left": `${offsetX}px`,
        "margin-top": `${offsetY}px`,
      };
      if (this.mode === Mode.CONTAIN) {
        style.maxWidth = style.maxHeight = "100%";
      }
      return style;
    },
  },
  watch: {
    initialIndex() {
      this.index = this.initialIndex;
    },
    index: {
      handler: function (val) {
        this.reset();
        this.onSwitch(val);
      },
    },
    currentImg(val) {
      this.$nextTick((_) => {
        const $img = this.$refs.img[0];
        if ($img && !$img.complete) {
          this.loading = true;
        }
      });
    },
  },
  mounted() {
    this.deviceSupportInstall();
    // add tabindex then wrapper can be focusable via Javascript
    // focus wrapper so arrow key can't cause inner scroll behavior underneath
    this.$refs["el-image-viewer__wrapper"].focus();
  },
  methods: {
    hide() {
      // this.deviceSupportUninstall()
      this.onClose();
    },
    deviceSupportInstall() {
      this._keyDownHandler = rafThrottle((e) => {
        const keyCode = e.keyCode;
        console.log(keyCode);
        switch (keyCode) {
          // ESC
          case 27:
            this.hide();
            break;
          // SPACE
          case 32:
            this.toggleMode();
            break;
          // LEFT_ARROW
          case 37:
            this.prev();
            break;
          // UP_ARROW
          case 38:
            this.handleActions("zoomIn");
            break;
          // RIGHT_ARROW
          case 39:
            this.next();
            break;
          // DOWN_ARROW
          case 40:
            this.handleActions("zoomOut");
            break;
        }
      });
      this._mouseWheelHandler = rafThrottle((e) => {
        const delta = e.wheelDelta ? e.wheelDelta : -e.detail;
        if (delta > 0) {
          this.handleActions("zoomIn", {
            // zoomRate: 0.01,
            zoomRate: 0.05, //修改放大缩小图片轴距
            enableTransition: false,
          });
        } else {
          this.handleActions("zoomOut", {
            // zoomRate: 0.01,
            zoomRate: 0.05,
            enableTransition: false,
          });
        }
      });
      on(
        this.$refs["el-image-viewer__wrapper"],
        "keydown",
        this._keyDownHandler
      );
      on(
        this.$refs["el-image-viewer__wrapper"],
        mousewheelEventName,
        this._mouseWheelHandler
      );
    },
    deviceSupportUninstall() {
      off(
        this.$refs["el-image-viewer__wrapper"],
        "keydown",
        this._keyDownHandler
      );
      off(
        this.$refs["el-image-viewer__wrapper"],
        mousewheelEventName,
        this._mouseWheelHandler
      );
      this._keyDownHandler = null;
      this._mouseWheelHandler = null;
    },
    handleImgLoad(e) {
      this.loading = false;
    },
    handleImgError(e) {
      this.loading = false;
      e.target.alt = "加载失败";
    },
    handleMouseDown(e) {
      if (this.loading || e.button !== 0) return;

      const { offsetX, offsetY } = this.transform;
      const startX = e.pageX;
      const startY = e.pageY;
      this._dragHandler = rafThrottle((ev) => {
        this.transform.offsetX = offsetX + ev.pageX - startX;
        this.transform.offsetY = offsetY + ev.pageY - startY;
      });
      on(
        this.$refs["el-image-viewer__wrapper"],
        "mousemove",
        this._dragHandler
      );
      on(this.$refs["el-image-viewer__wrapper"], "mouseup", (ev) => {
        off(
          this.$refs["el-image-viewer__wrapper"],
          "mousemove",
          this._dragHandler
        );
      });
      e.preventDefault();
    },
    reset() {
      this.transform = {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false,
      };
    },
    toggleMode() {
      if (this.loading) return;

      const modeNames = Object.keys(Mode);
      const modeValues = Object.values(Mode);
      const index = modeValues.indexOf(this.mode);
      const nextIndex = (index + 1) % modeNames.length;
      this.mode = Mode[modeNames[nextIndex]];
      this.reset();
    },
    imgsrcload() {
      let numadd = 0;
      let urlListnum = Number(this.urlList.length) - 1;
      let numnext = 0;
      if (this.index == 0) {
        numadd = Number(this.index) + 1;
        numnext = urlListnum;
      } else if (this.index == urlListnum) {
        numadd = 0;
        numnext = Number(this.index) - 1;
      } else {
        numadd = Number(this.index) + 1;
        numnext = Number(this.index) - 1;
      }
      this.imgsrc = this.urlList[numadd];
      this.imgsrcnext = this.urlList[numnext];
      console.log(this.imgsrc);
      console.log(this.imgsrcnext);
    },
    // 左右翻页 左
    prev() {
      if (this.isFirst && !this.infinite) return;
      const len = this.urlList.length;
      this.index = (this.index - 1 + len) % len;
    },
    next() {
      if (this.isLast && !this.infinite) return;
      const len = this.urlList.length;
      this.index = (this.index + 1) % len;
    },
    handleActions(action, options = {}) {
      if (this.loading) return;
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: 0.2,
        rotateDeg: 90,
        enableTransition: true,
        ...options,
      };
      const { transform } = this;
      switch (action) {
        case "zoomOut":
          if (transform.scale > 0.2) {
            transform.scale = parseFloat(
              (transform.scale - zoomRate).toFixed(3)
            );
          }
          break;
        case "zoomIn":
          transform.scale = parseFloat((transform.scale + zoomRate).toFixed(3));
          break;
        case "clocelise":
          transform.deg += rotateDeg;
          // this.$emit('edit', { ...transform })
          break;
        case "anticlocelise":
          transform.deg -= rotateDeg;
          break;
      }
      transform.enableTransition = enableTransition;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./viewer";

.imgnone {
  width: 0;
  height: 0;
}

.scale {
  font-size: 24px !important;
}

.svg-icon {
  cursor: pointer;
  font-size: 40px !important;
}

.delete {
  cursor: pointer;
  font-size: 40px !important;
}

.el-image-viewer__img {
  // border: 1px solid red;
  border-radius: 5px;
}
</style>
